import {isNull} from "@utils/stringUtil.ts";

class TokenStorage {
    expiration: Date;
    token: string;

    constructor(expiration: Date, token: string) {
        this.expiration = expiration;
        this.token = token
    }
}

export function saveToken(tokenName: string, token: string, expiration: Date) {
    if (isNull(tokenName)) return
    if (isNull(token)) {
        localStorage.removeItem(tokenName);
        return;
    }
    expiration = new Date(expiration)//进行转化,防止传入的是数字或者格式化的日期
    if (expiration && Date.now() > expiration.getTime()) {
        localStorage.removeItem(tokenName);
        return;
    }
    localStorage.setItem(tokenName, JSON.stringify(new TokenStorage(expiration, token)));
}

export function getToken(tokenName: string) {
    if (isNull(tokenName)) return 'null';
    try {
        const str = localStorage.getItem(tokenName);
        if (isNull(str)) {
            localStorage.removeItem(tokenName);
            return 'null';
        }
        if (typeof str !== "string") {
            localStorage.removeItem(tokenName);
            return 'null'
        }
        const token: TokenStorage = JSON.parse(str);

        if (token.expiration && Date.now() > new Date(token.expiration).getTime()) {
            localStorage.removeItem(tokenName);
            return 'null';
        }
        return token.token;
    } catch (e) {
        localStorage.removeItem(tokenName);
        return 'null';
    }
}


export function delToken(tokenName: string) {
    if (isNull(tokenName)) return
    localStorage.removeItem(tokenName);
}
